package com.mlethe.library.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by Mlethe on 2018/1/11.
 */
public class SortUtil {

    /**
     * ASCLL码从小到大排序
     *
     * @param map
     * @return
     */
    public static String sortToStringByASCLL(HashMap<String, Object> map) {
        if (map == null) {
            return null;
        }
        SortedMap<String, Object> parameters = new TreeMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            parameters.put(entry.getKey(), entry.getValue());
        }
        StringBuilder str = new StringBuilder();
        // ASCLL码从小到大排序
        for (SortedMap.Entry<String, Object> entry : parameters.entrySet()) {
            str.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
        return str.substring(1);
    }

    /**
     * ASCLL码从小到大排序
     *
     * @param map
     * @return
     */
    public static void sortByASCLL(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        SortedMap<String, Object> parameters = new TreeMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            parameters.put(entry.getKey(), entry.getValue());
        }
        // ASCLL码从小到大排序
        map.clear();
        for (SortedMap.Entry<String, Object> entry : parameters.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
    }
}
